<template>
  <a-spin :spinning="spinning">
    <page-header-wrapper v-if="!submitSuccess">
      <template v-slot:extra>
        <a-button type="primary" shape="round" @click="handleSubmit">{{ isAdd ? '点击申报' : '确认修改' }}</a-button>
        <a-button type="" shape="round" @click="handleReset">{{ isAdd ? '清空重新填写' : '取消修改' }}</a-button>
      </template>
      <div v-if="!spinning">
        <info ref="info" :data="editData" />
      </div>
    </page-header-wrapper>
    <transition enter-active-class="zoom_in">
      <a-card :bordered="false" v-if="submitSuccess">
        <a-result
          status="success"
          :title="$isEmpty($route.params.id) ? '提交成功' : '修改成功'"
          :sub-title="`自行备案${$isEmpty($route.params.id) ? '提交' : '修改'}成功。`"
        >
          <template #extra>
            <y-button type="success" @click="handleClick('close')"> 关闭当前页面 </y-button>
          </template>
        </a-result>
      </a-card>
    </transition>
  </a-spin>
</template>

<script>
import info from './info.vue'
import report from './report.vue'
import { postApplication, getHousesCount } from '@/api/communityReviewManagement'
import { getNewProposerbyID } from '@/api/common'
import cloneDeep from 'lodash.clonedeep'
export default {
  components: {
    report,
    info,
  },
  created() {
    this.isAdd = this.$isEmpty(this.$route.params.id)
    if (!this.isAdd) {
      this.fetchData()
    }
  },
  data() {
    return {
      isAdd: true,
      tabList: [{ key: 'info', tab: '保障用户基本信息' }],
      submitSuccess: false,
      spinning: false,
      editData: {},
    }
  },
  methods: {
    fetchData() {
      this.spinning = true
      getNewProposerbyID({
        ProposerID: this.$route.params.id,
      })
        .then((res) => {
          res.RegionNo = Number(res.RegionNo)
          res.TownshipNo = Number(res.TownshipNo)
          this.editData = res
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleClick(type) {
      if (type === 'close') {
        this.$multiTab.closeCurrentPage()
      } else {
        this.$multiTab.refresh()
      }
    },

    handleSubmit(e) {
      const infoSumbit = this.$refs.info.handleSubmit()
      Promise.all([infoSumbit])
        .then((res) => {
          const reportKey = {
            HousProperties: '',
            BurveyIfTestArea: '',
            BurveyBuildArea: '',
            BurveyAreaPer: '',
            BurveyIncome: '',
            HousProperty: '',
            BurveyNumber: '',
            BurveyVfyNumber: '',
            BeviewRemark: '',
            BeviewAgent: '',
            BeviewDate: '',
          }
          const data = cloneDeep({
            ...res[0],
            ...reportKey,
            ApplyNO: this.editData.ApplyNO || '',
            ID: this.editData.ID || '',
            LastAlterUserID: this.$store.getters.userid,
            Builder: this.editData.Builder || this.$store.getters.userid,
            proposerdelete: this.editData.proposerdelete || '',
          })
          this.$loading.show({
            tip: '正在查询房屋套数是否满足条件，请稍后...',
          })
          const { HousCategory, proposerdetailhouses, proposerdetail } = data
          const idCard = proposerdetail.find((e) => Number(e.Relation) === 0).IDCards
          getHousesCount({
            idcards: idCard,
            count: HousCategory === '承租公房' ? proposerdetailhouses.length || 0 : 0,
          })
            .then((resHouse) => {
              const state = resHouse[0].state
              if (state === '1') {
                this.$confirm({
                  title: '提示',
                  content: '房屋套数满足条件，是否提交？',
                  onOk: () => {
                    this.$loading.show({
                      tip: '提交中，请稍后...',
                    })
                    data.proposerdetail.forEach((element) => {
                      delete element.LiveDistrictAddressArr
                      delete element.censusRegister
                      if (['低保', '低收入'].includes(element.IfLowObjects)) {
                        element.IfLowObjects = '有'
                      } else {
                        element.IfLowObjects = '无'
                      }
                      if (Array.isArray(element.GroupOfApplicants)) {
                        element.GroupOfApplicants = element.GroupOfApplicants.join(',')
                      }
                    })
                    postApplication({
                      ProposerModules: data,
                      State: this.isAdd ? 'add' : 'update',
                    })
                      .then((res) => {
                        if (res.code == 200) {
                          this.submitSuccess = true
                          this.$eventBus.$emit('informationInputRefresh', this.isAdd)
                        }
                      })
                      .finally(() => {
                        this.$loading.hide()
                      })
                  },
                  onCancel() {},
                })
              }
            })
            .finally(() => {
              this.$loading.hide()
            })
        })
        .catch((err) => {
          this.$message.error({
            text: err,
          })
        })
    },
    handleReset() {
      if (this.isAdd) {
        this.$refs.info.handleReset()
      } else {
        this.$multiTab.closeCurrentPage()
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .card-title {
  font-size: 20px;
  font-weight: bold;
}
</style>
